// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import $ from 'jquery'
import db from './db'
import App from './App'
import 'vue-awesome/icons'
import Icon from 'vue-awesome/components/Icon'
import utils from "./plugin/utils"

Vue.config.productionTip = false

Vue.use(utils)

void function() {
  var _originalPost = $.post;
  $.post = function() {
    $.post.before.fireWith(this, arguments);
    return _originalPost
      .apply(this, arguments)
      .done($.post.done.fire)
      .fail($.post.fail.fire)
      .always($.post.after.fire);
  };
  var option = "memory unique stopOnFalse";
  $.post.before = $.Callbacks(option);
  $.post.after = $.Callbacks(option);
  $.post.done = $.Callbacks(option);
  $.post.fail = $.Callbacks(option);
  $.post.orginal = _originalPost;
}();
  

var loadApp = function() {
    return db.load().progress(x => {
      switch(x) {
        case 'directory':
          window.loadTo(45);
          break;
        case 'tag':
          window.loadTo(70);
          break;
        case 'image':
          window.loadTo(85);
          break;
      }
    });
}

var directory_name = '/directory';

function formatPath(path) {
    return '/directory' + path;
}

function parsePath(path) {
    return decodeURI(path).replace(/^\/directory/, '');
}

function pushState(name, path) {
    window.history.pushState(
      null,
      name,
      formatPath(path)
    );
}

function replaceState(name, path) {
    window.history.replaceState(
      null,
      name,
      formatPath(path)
    );
}

if (window.location.pathname == '/') {
    pushState('directory', '/');
}

loadApp().then(function() {
    var app = new Vue({
      el: '#app',
      data: {
        db: db.data,
        path: parsePath(window.location.pathname)
      },
      components: { App },
      template: '<App :db="db" :root="db.directory.$Root" :path="path" @pathNotFound="pathNotFound" @directoryChange="directoryChange" @directoryReplace="directoryReplace"/>',
      methods: {
        directoryChange(newItem) {
            var newPath = newItem.path;
            pushState(newItem.value, newPath);
            this.path = newPath;
        },
        directoryReplace(newItem) {
          var newPath = newItem.path;
          replaceState(newItem.value, newPath);
          this.path = newPath;
        },
        pathNotFound(to_path, oldPath) {
            this.path = parsePath(to_path);
            pushState('directory', to_path);
        }
      }
    });
    app.$nextTick(() => {
        window.appStart();
    })

    window.addEventListener('popstate', () => {
      app.path = parsePath(window.location.pathname);
    })

})
